package com.letv.core.network.volley;

import java.util.concurrent.BlockingQueue;

import android.os.Process;

import com.letv.core.network.volley.VolleyRequest.RequestManner;
import com.letv.core.network.volley.listener.Network;
import com.letv.core.network.volley.listener.ResponseDelivery;

/**
 * 网络调度器
 * 
 * @author zhuqiao
 * 
 */
public class NetworkDispatcher extends Thread {
    private final ResponseDelivery mDelivery;
    private final BlockingQueue<VolleyRequest<?>> mNetworkQueue;
    private final BlockingQueue<VolleyRequest<?>> mCacheQueue;// 缓存请求队列
    private final Network mNetwork;

    private volatile boolean mQuit = false;

    public NetworkDispatcher(BlockingQueue<VolleyRequest<?>> networkQueue, BlockingQueue<VolleyRequest<?>> cacheQueue,
            Network network, ResponseDelivery delivery) {
        mNetworkQueue = networkQueue;
        mCacheQueue = cacheQueue;
        mNetwork = network;
        mDelivery = delivery;
    }

    public void quit() {
        mQuit = true;
        // 通知线程中断
        interrupt();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void run() {
        // 设置线程优先级为后台，这样当多个线程并发后很多无关紧要的线程分配的CPU时间将会减少，有利于主线程的处理
        Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
        while (true) {
            VolleyRequest<?> request;
            try {
                // 不断把reqeust从请求队列中拿出来
                // PriorityBlockingQueue的take方法会把元素拿出来并移除，并且是Lock同步的
                request = mNetworkQueue.take();

                new NetworkRequestData(mDelivery, mNetwork, false).start(request);

                if (request.mRequestType == RequestManner.NETWORK_THEN_CACHE) {
                    // 不管成功还是失败，都需要去缓存再获取一遍
                    mCacheQueue.put(request);
                }
            } catch (InterruptedException e) {
                if (mQuit) {
                    return;
                }
                continue;
            }
        }
    }

}
